<?php
/*
 * @Description    : HTTP返回
 * @Version        : 1.0.0
 * @Author         : QianLong
 * @Date           : 2021-08-25 14:19:36
 * @LastEditors    : QianLong
 * @LastEditTime   : 2023-01-11 13:06:45
 */

declare(strict_types=1);

namespace App\Kernel\Http;

use Hyperf\HttpMessage\Cookie\Cookie;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Context\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface as PsrResponseInterface;

class Response
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var ResponseInterface
     */
    protected $response;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->response = $container->get(ResponseInterface::class);
    }

    /**
     * @param $data
     * @return PsrResponseInterface
     */
    public function json(int $code, string $msg = 'Fail', $dat = [])
    {
        $dat = $dat ? $dat : (object)$dat;
        $data['code'] = $code;
        $data['data'] = $dat;
        $data['msg'] = $msg;
        unset($code,$dat,$msg);
        if ($data['code'] !== 200 && $data['code'] !== '200') {
            $requestId = createId('RFR');
            $data['request_id'] = $requestId;
            requestFailLog($data,$requestId);
        }
        return $this->response->json($data)->withHeader('Content-Type', 'application/json; charset=utf-8');
    }
    /**
     * @param $data
     * @return PsrResponseInterface
     */
    public function raw(string $data = 'success')
    {
        return $this->response->raw($data)->withHeader('Content-Type', 'text/html; charset=utf-8');
    }
    public function png(string $data = 'success')
    {
        return $this->response->raw($data)->withHeader('Content-Type', 'image/png;');
    }

    public function redirect($url, $status = 302)
    {
        return $this->response()
            ->withAddedHeader('Location', (string) $url)
            ->withStatus($status);
    }

    public function cookie(Cookie $cookie)
    {
        $response = $this->response()->withCookie($cookie);
        Context::set(PsrResponseInterface::class, $response);
        return $this;
    }

    /**
     * @return \Hyperf\HttpMessage\Server\Response
     */
    public function response()
    {
        return Context::get(PsrResponseInterface::class);
    }
}
